<template>
  <el-container style="padding: 20px">
    <el-main>
      <el-card>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span style="font-weight: bold">未核查疫苗列表</span>
          <el-button
            type="primary"
            :disabled="selectedVaccines.length === 0"
            @click="openAssignDialog"
          >
            分配给核查员
          </el-button>
        </div>

        <el-table
          :data="unassignedVaccines"
          @selection-change="handleSelectionChange"
          style="margin-top: 20px"
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="numbering" label="疫苗编号" />
          <el-table-column prop="name" label="疫苗名称" />
          <el-table-column
            prop="productionDate"
            label="生产日期"
            :formatter="formatDate"
          />
        </el-table>
      </el-card>

      <!-- 分配对话框 -->
      <el-dialog v-model="assignDialogVisible" title="选择核查员" width="400px">
        <el-form>
          <el-form-item label="核查员">
            <el-select
              v-model="selectedCheckerId"
              placeholder="请选择核查员"
              style="width: 100%"
            >
              <el-option
                v-for="checker in checkerList"
                :key="checker.id"
                :label="checker.name + '（' + checker.email + '）'"
                :value="checker.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="assignVaccines"
            :disabled="!selectedCheckerId"
          >
            确认分配
          </el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const checkerList = ref([])
const unassignedVaccines = ref([])
const selectedVaccines = ref([])
const selectedCheckerId = ref(null)
const assignDialogVisible = ref(false)

const currentPage = ref(1)
const pageSize = ref(10)

// 获取核查员列表
async function fetchCheckerList() {
  try {
    const res = await axios.get('http://127.0.0.1:8181/users/checkers')
    checkerList.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取核查员列表失败')
  }
}

// 获取未分配疫苗列表（分页）
async function fetchUnassignedVaccines() {
  try {
    const res = await axios.get(
      `http://127.0.0.1:8181/checkTasks/unassignedVaccines/${currentPage.value}/${pageSize.value}`
    )
    unassignedVaccines.value = res.data.data.data || []
  } catch (error) {
    ElMessage.error('获取未分配疫苗列表失败')
  }
}

// 勾选疫苗
function handleSelectionChange(selection) {
  selectedVaccines.value = selection
}

// 打开分配对话框
function openAssignDialog() {
  if (selectedVaccines.value.length === 0) {
    ElMessage.warning('请先选择要分配的疫苗')
    return
  }
  assignDialogVisible.value = true
}

// 分配疫苗给核查员
async function assignVaccines() {
  if (!selectedCheckerId.value) {
    ElMessage.warning('请选择核查员')
    return
  }
  const assignedNumberings = selectedVaccines.value.map((v) => v.numbering)
  try {
    await axios.post('http://127.0.0.1:8181/checkTasks/assign', {
      checkerId: selectedCheckerId.value,
      vaccines: assignedNumberings,
    })
    ElMessage.success(`已分配 ${assignedNumberings.join(', ')} 给核查员`)
    assignDialogVisible.value = false
    selectedVaccines.value = []
    selectedCheckerId.value = null
    fetchUnassignedVaccines()
  } catch (error) {
    ElMessage.error('分配失败，请稍后重试')
  }
}

// 日期格式化函数
function formatDate(row, column, cellValue) {
  if (!cellValue) return ''
  const date = new Date(cellValue)
  const yyyy = date.getFullYear()
  const mm = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}

// 初始化加载数据
onMounted(() => {
  fetchCheckerList()
  fetchUnassignedVaccines()
})
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
